﻿using MiniExcelLibs;

namespace Digitalmes.Infrastructure.IO;

/// <summary>
/// MiniExcel 导出。
/// </summary>
public sealed class MiniExcelExport : IExcelExport
{
    public void SaveAs<T>(string path, IEnumerable<T> data, ExcelExportOptions? options = null)
    {
        options ??= new();
        MiniExcel.SaveAs(path, data, excelType: options.ExcelType);
    }

    public async Task SaveAsAsync<T>(string path, IEnumerable<T> data, ExcelExportOptions? options = null, CancellationToken cancellationToken = default)
    {
        options ??= new();
        await MiniExcel.SaveAsAsync(path, data, sheetName: options.SheetName, excelType: options.ExcelType, cancellationToken: cancellationToken);
    }

    public Stream SaveAsStream<T>(IEnumerable<T> data, ExcelExportOptions? options = null)
    {
        options ??= new();

        MemoryStream ms = new();
        ms.SaveAs(data, sheetName: options.SheetName, excelType: options.ExcelType);
        ms.Seek(0, SeekOrigin.Begin);

        return ms;
    }

    public async Task<Stream> SaveAsStreamAsync<T>(IEnumerable<T> data, ExcelExportOptions? options = null, CancellationToken cancellationToken = default)
    {
        options ??= new();

        MemoryStream ms = new();
        await ms.SaveAsAsync(data, sheetName: options.SheetName, excelType: options.ExcelType, cancellationToken: cancellationToken);
        ms.Seek(0, SeekOrigin.Begin);

        return ms;
    }
}
